package com.fjwt.gz.province.changchun;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.common.utils.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.province.changchun.encrypt.*;
import com.fjwt.gz.province.inter.BankCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 手机银行是否绑定
 * 快捷支付是否开通
 * 两个功能是一起的接口
 */
@Slf4j
@Service
public class JilinBankCardService implements BankCardService {

    /**
     * 手机银行和快捷支付是否开通
     **/
    public JSONObject getBankCardInfo(@NonNull List<JSONObject> jsonObjects) {
        log.debug("手机银行和快捷支付是否开通查询参数：{}", JSONUtil.toJsonStr(jsonObjects));
        try {
            JSONObject respJsonObject = this.queryInfo(jsonObjects, ChangchunKit.USER_BANK_PAYMENT_URL);
            return respJsonObject;
        } catch (Exception e) {
            throw new BizException("数据查询失败");
        }
    }

    /**
     * 获取开卡日期
     */
    @Override
    public JSONObject getBankCardOpenDt(List<JSONObject> jsonObjects) {
        try {
            List<String> list = new ArrayList<>();
            Map<String, String> params = new HashMap<>();
            for (int i = 0; i < jsonObjects.size(); i++) {
                String encryption = AesUtil.encrypt(String.valueOf(jsonObjects.get(i)));
                list.add(encryption);
                params.put("param" + (i + 1), encryption);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(list);
            log.debug("JSON RequestBody: {}", json);
            String sign = SignatureUtil.generateSignature(params, SignVerifyFilter.SECRET_KEY);
            Boolean a = SignatureUtil.verifySignature(params, SignVerifyFilter.SECRET_KEY, sign);
            log.debug("验签结果：{}", a);
            log.debug("接口地址：{}", ChangchunKit.USER_BANK_OPENDT_URL);

            return this.post(json, ChangchunKit.USER_BANK_OPENDT_URL, sign);
        }catch (Exception e) {
            log.info("吉林获取开卡日期异常：{}", e.getMessage());
            throw new BizException("数据查询失败");
        }
    }

    /**
     * 是否满足存款提升额度条件
     */
    @Override
    public JSONObject getBankCardDeposit(List<JSONObject> jsonObjects) {
        try {
            List<String> list = new ArrayList<>();
            Map<String, String> params = new HashMap<>();
            for (int i = 0; i < jsonObjects.size(); i++) {
                String encryption = AesUtil.encrypt(String.valueOf(jsonObjects.get(i)));
                list.add(encryption);
                params.put("param" + (i + 1), encryption);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(list);
            log.debug("JSON RequestBody: {}", json);
            String sign = SignatureUtil.generateSignature(params, SignVerifyFilter.SECRET_KEY);
            Boolean a = SignatureUtil.verifySignature(params, SignVerifyFilter.SECRET_KEY, sign);
            log.debug("验签结果：{}", a);
            log.debug("接口地址：{}", ChangchunKit.USER_BANK_DEPOSIT_URL);

            return this.post(json, ChangchunKit.USER_BANK_DEPOSIT_URL, sign);
        }catch (Exception e) {
            log.info("吉林获取是否满足存款提升额度条件异常：{}", e.getMessage());
            throw new BizException("数据查询失败");
        }
    }

    /**
     * 手机银行和快捷支付是否开通
     */
    private JSONObject queryInfo(List<JSONObject> jsonObjects, String url) throws Exception {
        List<String> list = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        for (int i = 0; i < jsonObjects.size(); i++) {
            String encryption = AesUtil.encrypt(String.valueOf(jsonObjects.get(i)));
            list.add(encryption);
            params.put("param" + (i + 1), encryption);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(list);
        log.debug("JSON RequestBody: {}", json);
        String sign = SignatureUtil.generateSignature(params, SignVerifyFilter.SECRET_KEY);
        Boolean a = SignatureUtil.verifySignature(params, SignVerifyFilter.SECRET_KEY, sign);
        log.debug("验签结果：{}", a);
        log.debug("接口地址：{}", url);

        return this.post(json, url, sign);
    }

    private JSONObject post(String param, String url, String sign) throws Exception {
        HttpResponse response = null;
        try {
            HttpRequest body = HttpRequest.post(url)
                    .header("Content-Type", "application/json;charset=utf-8")
                    .header(SignVerifyFilter.SIGNATURE_HEADER, sign)
                    .timeout(20000)
                    .body(param);
            response = body.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }
        if (response == null || response.body() == null) {
            throw new BizException("网络连接异常,请稍后重试");
        }
        log.debug("响应结果：{}", response.body());
        JSONObject respData = JSONObject.parseObject(response.body());
        if (200 != respData.getInteger("code")) {
            throw new BizException(respData.getString("msg"));
        }
        if (respData.getInteger("total") == null || respData.getInteger("total") < 1) {
            return new JSONObject();
        }

        String decrypt = null;
        try {
            decrypt = RsaFgmUtils.decryptByPublicKey(RsaFgmUtils.publicKey, respData.getString("data"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("数据解密失败");
        }
        if (StringUtils.isNullOrEmpty(decrypt)) {
            throw new BizException("数据解密失败");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        JSONArray decryptList = objectMapper.readValue(decrypt, JSONArray.class);
        log.debug("解密后,用户情况：decryptList：{}", decryptList);
        return decryptList.getObject(0, JSONObject.class);
    }
}
